package com.ty.xiaoyu.service.impl;

import com.ty.xiaoyu.entity.BrowsingHistory;
import com.ty.xiaoyu.entity.Module;
import com.ty.xiaoyu.exception.BrowsingHistoryOperationException;
import com.ty.xiaoyu.service.BrowsingHistoryService;
import com.ty.xiaoyu.util.MyTimeUtil;
import com.ty.xiaoyu.util.RandomIdUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BrowsingHistoryServiceImpl extends BaseService implements BrowsingHistoryService {
    @Override
    public List<BrowsingHistory> getListByUserId(String userId) throws BrowsingHistoryOperationException {
        List<BrowsingHistory> browsingHistoryList = browsingHistoryMapper.queryListByUserId(userId);
        if (CollectionUtils.isEmpty(browsingHistoryList)) {
            throw new BrowsingHistoryOperationException("浏览记录为空");
        }
        return browsingHistoryList;
    }

    @Override
    public void addHistory(BrowsingHistory history) throws BrowsingHistoryOperationException {
        history.setHistoryId(RandomIdUtil.getId());
        history.setHistoryState(1);
        history.setCreatTime(MyTimeUtil.nowTime());
        history.setLastUpdateTime(MyTimeUtil.nowTime());
        Integer state = browsingHistoryMapper.insertHistory(history);
        if (state <= 0) {
            throw new BrowsingHistoryOperationException("添加浏览记录失败");
        }
    }

    @Override
    public void modifyHistory(BrowsingHistory history) throws BrowsingHistoryOperationException {
        history.setLastUpdateTime(MyTimeUtil.nowTime());
        Integer state = browsingHistoryMapper.updateHistory(history);
        if (state <= 0) {
            throw new BrowsingHistoryOperationException("更新浏览记录失败");
        }
    }

    @Override
    public BrowsingHistory getHistoryId(String userId, String moduleId, String topicId) {
        return browsingHistoryMapper.queryHistoryId(userId, moduleId, topicId);
    }

    @Override
    public List<Module> getHistoryListOfModuleByUserId(String userId) throws BrowsingHistoryOperationException {
        List<Module> moduleList = browsingHistoryMapper.queryHistoryListOfModuleByUserId(userId);
        System.out.println(moduleList.size());
        if (moduleList == null || moduleList.isEmpty()) {
            throw new BrowsingHistoryOperationException("模块浏览记录为空");
        }
        return moduleList;
    }

    @Override
    public void deleteHistoryById(String historyId) throws BrowsingHistoryOperationException {
        Integer state = browsingHistoryMapper.deleteHistoryById(historyId, MyTimeUtil.nowTime());
        if (state <= 0) {
            throw new BrowsingHistoryOperationException("删除帖子失败");
        }
    }
}
